import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Form, Input, Button, notification, message, Modal } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";
import ProblemPage from './ProblemPage';
import ProblemDetail from './ProblemDetail';
import { DropDownSelect } from '@/components/DropDownSelect/index';
import { DICT } from '../enum';
import { queryInfoById } from '../service';

const {confirm} = Modal;

interface Props extends FormComponentProps {
  dispatch?: Function,
  data?: {
    id: number
  },
  keys?: Array<string>,
  dict?: any,
  data_id?: any,
}

@connect(({ report_template }) => ({
  dict: report_template.dict
}))

class TemplateFrom extends Component<Props, any> {
  state = {
    templateList: [],
    visible: false,
    groupVisible: false,
    isReset: false,
    rowData: [],
    selectdIndex: null,
    groupIndex: null,
    index: 0,
    updateData: {
      name: null,
      childType: null,
      groupList: null
    },
    updateGroupList: []
  };

  componentWillMount() {
    const { dispatch, data_id, form } = this.props;
    dispatch({
      type: 'report_template/queryDict',
      payload: {
        keyList: DICT
      }
    });
    if(!data_id) {
      return;
    }
    let hasMsg = message.loading('');
    queryInfoById(data_id).then(data => {
      let updateData = {
        id: data.id,
        name: data.name,
        childType: data.childType,
        groupList: data.groupList
      };
      this.setState({
        updateData
      }, () => {
        let name = this.state.updateData.name;
        let childType = this.state.updateData.childType;
        let updateGroupList = [], templateList = [];
        form.setFieldsValue({name, childType});
        this.state.updateData.groupList.forEach((item) => {
          templateList.push(this.state.index);
          updateGroupList.push(item.name);
          this.setState({
            ['group' + this.state.index]: item.reportTemplateQuestionList,
            ['groupLen' + this.state.index]: item.reportTemplateQuestionList.length
          });
          this.state.index ++;
        });
        this.setState({
          templateList,
          updateGroupList
        }, hasMsg)
      })
    });
  }

  selectQuestion(index, item) {
    if(this.state.selectdIndex === item) {
      this.setState({
        visible: true
      });
    }else {
      this.setState({
        visible: true,
        isReset: true,
        selectdIndex: item
      }, () => {
        this.setState({
          isReset: false
        })
      });
    }
  }

  groupQuestion(index) {
    if(!this.state['groupLen' + index]) {
      message.warning('请选择题目后操作', 1.5);
      return;
    }
    if(this.state.groupIndex !== index) {
      this.state.groupIndex = index;
      this.setState({
        groupVisible: true,
        isReset: true
      }, () => {
        this.setState({
          isReset: false
        })
      });
    }else{
      this.setState({
        groupVisible: true
      });
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    let isAll = true;
    let template_iup = document.querySelectorAll('.template_iup');
    if(template_iup.length === 0) {
      message.warning('请添加题目组');
      return;
    }
    template_iup.forEach(item => {
      if(!item['value'].trim()) {
        isAll = false;
      }
    });
    if(isAll) {
      const { form, dispatch, data_id } = this.props;
      let params = {name: '', type: '', childType: '', groups: [], id: ''}, groups = [];
      form.validateFields((err, values) => {
        if(!err) {
          params.name = values.name;
          params.type = '2';
          params.childType = values.childType;
          this.state.templateList.forEach((item, index) => {
            let questions = [];
            if(this.state['group' + item].length === 0) {
              isAll = false;
            }
            this.state['group' + item].forEach(g_item => {
              questions.push(g_item.id);
            });
            groups.push({
              name: template_iup[index]['value'],
              questions: questions
            })
          });
          if(!isAll) {
            message.warning('请选择题目', 1.5);
            return;
          }
          params.groups = groups;
          if(!!data_id) {
            params.id = data_id;
            dispatch({
              type: 'report_template/update',
              payload: params
            });
          }else {
            dispatch({
              type: 'report_template/create',
              payload: params
            });
          }
        }

      })
    }else {
      message.warning('请填写完整', 1.5);
      return;
    }
  };
  handleOk = () => {
    let len = this.state.rowData.length;
    this.state['group' + this.state.selectdIndex] = this.state.rowData;
    this.setState({
      visible: false,
      rowData: [],
      ['groupLen' + this.state.selectdIndex]: len,
    });
    return;
  };
  handleCancel = () => {
    this.setState({
      visible: false,
      isReset: true
    }, () => {
      this.setState({
        isReset: false
      })
    });
  };

  handleGroupCancel = () => {
    this.setState({
      groupVisible: false,
    });
  };

  delConfirm(index, item) {
    let that = this;
    confirm({
      title: '删除',
      content: '是否删除该题目组？',
      onOk() {
        that.state.templateList.splice(index, 1);
        that.state['groupLen' + item] = null;
        that.setState({
          templateList: that.state.templateList,
          ['group' + item]: null
        })
      },
      onCancel() {},
      okText: "确认",
      cancelText: "取消"
    });
  }

  render() {
    const { form, data_id, dict } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 8 },
      },
    };
    const formItemButton = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 8 },
        offset: 6,
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 12,
          offset: 0,
        },
        sm: {
          span: 8,
          offset: 4,
        },
      },
    };
    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          <Form.Item
            {...formItemLayout}
            label="报表名称"
          >
            {getFieldDecorator('name', {
              rules: [{
                required: true, message: '报表名称',
              }],
            })(
              <Input placeholder='请输入报表名称'/>
            )}
          </Form.Item>
          <Form.Item
            className={data_id ? 'none' : ''}
            {...formItemLayout}
            label="报表类型"
          >
            {
              getFieldDecorator('childType', {
                rules: [{
                  required: true, message: '报表类型',
                }],
              })(
                DropDownSelect(dict, 'device.dtype', '', '100%', '', true)
              )
            }
          </Form.Item>
          {
            this.state.templateList.map((item, index) => (
              <Form.Item
                {...formItemLayout}
                key={item}
                label={`题目组${index + 1}`}
              >
                <div>
                  <Input
                    placeholder='请输入题目组标题'
                    className="template_iup"
                    defaultValue={this.state.updateGroupList[index] ? this.state.updateGroupList[index] : ''}
                  />
                  <Button
                    type="dashed"
                    icon='minus'
                    onClick={this.delConfirm.bind(this, index, item)}
                  >删除</Button>
                  <Button
                    type="dashed"
                    icon='plus'
                    style={{'marginLeft': '15px'}}
                    onClick={this.selectQuestion.bind(this, index, item)}
                  >选择题目</Button>
                  <Button
                    type="dashed"
                    icon='check'
                    style={{'marginLeft': '15px'}}
                    onClick={this.groupQuestion.bind(this, index)}
                  >已选择题目(<span id={`group${index}`}>{this.state['groupLen' + item] ? this.state['groupLen' + item] : 0}</span>)</Button>
                </div>
              </Form.Item>
            ))
          }
          <Form.Item
            {...formItemButton}
            style={{'marginBottom': '30px'}}
          >
            <Button type="dashed" icon='plus' style={{'width': '100%'}} onClick={
              () => {
                this.state.templateList.push(this.state.index);
                this.setState({
                  templateList: this.state.templateList,
                  ['group' + this.state.index]: [],
                  ['groupLen' + this.state.index]: 0
                }, () => {
                  this.state.index ++;
                })
              }
            }>添加题目组</Button>
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">{ !!data_id ? '修改' : '新增' }</Button>
            <Link to='/data/report_template'>
              <Button style={{ marginLeft: '5%' }}>返回</Button>
            </Link>
          </Form.Item>
        </Form>
        <Modal
          title="所有问题"
          width={800}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="确认"
          cancelText="取消"
        >
          <ProblemPage
            isReset={this.state.isReset}
            onChange={ (rowData) => {
              this.setState({
                rowData
              })
            } }
          />
        </Modal>
        <Modal
          title="已选择的题目"
          visible={this.state.groupVisible}
          onOk={this.handleGroupCancel}
          onCancel={this.handleGroupCancel}
          okText="确认"
          cancelText="取消"
        >
          <ProblemDetail
            groupData={this.state['group' + this.state.groupIndex]}
          />
        </Modal>
      </div>
    );
  }
}

const FormList = Form.create()(TemplateFrom);
export default FormList;
